package com.cskaoyan.service;

import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.MarketUserExample;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.common.User;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author stone
 * @date 2022/06/25 11:11
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Override
    public CommonData<User> query(String username, BasePageInfo info) {
        /*PageHelper.startPage(info.getPage(), info.getLimit());
        if (username != null) {
            username = "%" + username + "%";
        }
        List<User> users = userMapper.select(username, info.getSort(), info.getOrder());
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return CommonData.data(pageInfo);*/

        // 根据用户名做一个查询
        MarketUserExample example = new MarketUserExample();
        MarketUserExample.Criteria criteria = example.createCriteria();

        //条件查询，username不为空的情况下，才根据username去做模糊查询
        if (username != null) {
            criteria.andUsernameLike("%" + username + "%");
        }

        //criteria.andUsernameEqualTo("songge");//向criteria中添加一条Criterion
        //criteria.andPasswordEqualTo("niupi");

        /*criteria.andUsernameEqualTo("songge")
                .andPasswordEqualTo("niupi")
                .andAvatarBetween("a","b");*/

        /*StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("hello").append("world").append("");*/

        //example.setOrderByClause("id desc");
        // add_time desc
        example.setOrderByClause(info.getSort() + " " + info.getOrder());

        //在执行查询之前开启分页
        PageHelper.startPage(info.getPage(),info.getLimit());
        // 比如page=1 limit=4         select .....  limit 4
        // 比如page=2 limit=4         select .....  limit 4,4
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(example);
        // 分页结果
        PageInfo pageInfo = new PageInfo(marketUsers);//必须是原始的查询结果
        // total >= limit
        // 如果不满一页 total就小于limit了

        /*ArrayList<MarketUser> users = new ArrayList<>();
        for (MarketUser marketUser : marketUsers) {
            users.add(marketUser);
        }
        PageInfo<MarketUser> marketUserPageInfo = new PageInfo<>(users);//是有问题的*/

        /*int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        List list = pageInfo.getList();*/

        return CommonData.data(pageInfo);
    }
    // total 和 list.size() 之间的关键
    // total ≥ list.size()
}
